package com.keelau.config.dataconfig;

import com.keelau.config.MyBatisBeanConfig;
import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.*;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.inject.Inject;
import javax.sql.DataSource;

@Configuration
@ComponentScan("com.keelau.*")
@PropertySource("classpath:config.properties")
@Import(MyBatisBeanConfig.class)
public class MyBatisConfig implements EnvironmentAware {

    @Inject
    Environment env;

    @Bean
    public  DataSource dataSource(){
        BasicDataSource bd = new BasicDataSource();
        bd.setDriverClassName(env.getProperty("mysql.driverclassname"));
        bd.setUrl(env.getProperty("mysql.url"));
        bd.setUsername(env.getProperty("mysql.username"));
        bd.setPassword(env.getProperty("mysql.passoword"));
        bd.setInitialSize(Integer.parseInt(env.getProperty("mysql.init")));
        bd.setMaxIdle(Integer.parseInt(env.getProperty("mysql.max")));
        return  bd;
    }

     @Bean
    public  org.apache.ibatis.session.Configuration mybatisConfiguration(){
         org.apache.ibatis.session.Configuration mybatisConfiguration = new org.apache.ibatis.session.Configuration();
         mybatisConfiguration.setMapUnderscoreToCamelCase(true);
         return mybatisConfiguration;
     }

      @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(){
         MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
         mapperScannerConfigurer.setBasePackage("com.keelau.idao");
         return  mapperScannerConfigurer;
      }

    @Bean
    public SqlSessionFactory sqlSessionFactoryBean(DataSource dataSource, org.apache.ibatis.session.Configuration configuration) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        //创建工厂
        sqlSessionFactoryBean.setDataSource(dataSource);
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[] resources = resolver.getResources("classpath*:com/keelau/idao/mapping/**/*Dao.xml");
        //扫描xml
        sqlSessionFactoryBean.setMapperLocations(resources);
        sqlSessionFactoryBean.setConfiguration(configuration);
        return sqlSessionFactoryBean.getObject();
    }

    @Override
    public void setEnvironment(Environment environment) {
        env = environment;
    }
}
